﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using KPIS.DBM;
using KPIS.GERP.GHRMS.MODEL;
using KPIS.GERP.GHRMS.IDAL;

namespace KPIS.GERP.GHRMS.DAL
{
    public sealed class MasDistrictDAL : IMasDistrictDAL
    {
        IDBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);

        public MasDistrictDAL()
        {

        }
        public DataSet LoadDistricts(Nullable<int> Sequence, Nullable<int> Amphur, Nullable<int> Province, string SearchText)
        {
            string strSQL;

            DataSet ds = null;

            try
            {
                dbManager.Open();


                strSQL = "SELECT d.*"
                        + ", a.AMP_NAME, a.PROV_SEQ, p.PROV_NAME"
                        + ", CONCAT('ตำบล', d.DISTRICT_NAME, ' อำเภอ', a.AMP_NAME, ' จังหวัด', p.PROV_NAME)"
                            + " AS DIS_AMP_PROV"
                        + ", CONCAT('ตำบล', d.DISTRICT_NAME, ' อำเภอ', a.AMP_NAME)"
                            + " AS DIS_AMP"
                     + " FROM MAS_DISTRICTS d"
                     + " LEFT JOIN MAS_AMPHURS a ON d.AMP_SEQ = a.AMP_SEQ"
                     + " LEFT JOIN MAS_PROVINCES p ON a.PROV_SEQ = p.PROV_SEQ"
                     + " WHERE d.RECORD_STATUS not like @DeleteRecord"
                     + (Sequence.HasValue ? " AND d.DISTRICT_SEQ = @Sequence" : "")
                     + (Amphur.HasValue ? " AND d.AMP_SEQ = @Amphur" : "")
                     + (Province.HasValue ? " AND a.PROV_SEQ = @Province" : "")
                    //+ " AND CASE WHEN @SearchText = '' THEN 0 = 0"
                    //   + " ELSE (d.DISTRICT_NAME LIKE CONCAT('%', @SearchText , '%')"
                    //       + " OR a.AMP_NAME LIKE CONCAT('%', @SearchText , '%')"
                    //       + " OR p.PROV_NAME LIKE CONCAT('%', @SearchText , '%')"
                    //       + ") END"
                    //+ " ORDER BY d.DISTRICT_NAME";
                     ;

/** Fixed by Tiger 2013/09/11                
    Statement error when used with SQLServer 
 */
                if (!SearchText.Trim().Equals(""))
                {
                    dbManager.CreateParameters(5);
                    dbManager.AddParameters(0, "@DeleteRecord", SystemInfo._DeleteRecordStatus);
                    dbManager.AddParameters(1, "@Sequence", Sequence);
                    dbManager.AddParameters(2, "@Amphur", Amphur);
                    dbManager.AddParameters(3, "@Province", Province);
                    dbManager.AddParameters(4, "@SearchText", SearchText);
                    strSQL += " AND (d.Name LIKE CONCAT('%', @SearchText , '%')"
                          + " OR a.Name LIKE CONCAT('%', @SearchText , '%')"
                          + " OR p.Name LIKE CONCAT('%', @SearchText , '%')"
                          + ")"
                          ;
                }
                else
                {
                    dbManager.CreateParameters(4);
                    dbManager.AddParameters(0, "@DeleteRecord", SystemInfo._DeleteRecordStatus);
                    dbManager.AddParameters(1, "@Sequence", Sequence);
                    dbManager.AddParameters(2, "@Amphur", Amphur);
                    dbManager.AddParameters(3, "@Province", Province);
                }

                ds = dbManager.ExecuteDataSet(CommandType.Text, strSQL);                
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                dbManager.CloseReader();
                dbManager.Dispose();
            }
            return ds;
        }
        public IList<MasDistrictInfo> ListDistricts(MasDistrictInfo distInfo)
        {
            string strSQL;
            int ampSeq = 0;
            int proSeq = 0;
            if (distInfo.Amphurs != null)
            {
                ampSeq = distInfo.Amphurs.Sequence;
                proSeq = distInfo.Amphurs.Provinces == null ? 0 : (int) distInfo.Amphurs.Provinces.Sequence;
            }
            IList<MasDistrictInfo> infoList = new List<MasDistrictInfo>();
            try
            {
                dbManager.Open();
                dbManager.CreateParameters(4);

                dbManager.AddParameters(0, "@DeleteRecord", SystemInfo._DeleteRecordStatus);
                dbManager.AddParameters(1, "@Seq", distInfo.Sequence);
                dbManager.AddParameters(2, "@Amphur", ampSeq);
                dbManager.AddParameters(3, "@Province", proSeq);

                strSQL = "SELECT d.DISTRICT_SEQ, d.DISTRICT_NAME, d.DISTRICT_NAME_ENG, d.AMP_SEQ"
                        + ", d.CREATED_BY, d.UPDATED_BY"
                     + " FROM MAS_DISTRICTS d"
                     + " LEFT JOIN MAS_AMPHURS a ON d.AMP_SEQ = a.AMP_SEQ"
                     + " WHERE d.RECORD_STATUS not like @DeleteRecord"                    
                     + (distInfo.Sequence > 0 ? " AND d.DISTRICT_SEQ = @Seq" : "")
                     + (ampSeq > 0 ? " AND d.AMP_SEQ = @Amphur" : "")
                     + (proSeq > 0 ? " AND a.PROV_SEQ = @Province" : "")
                     + " ORDER BY DISTRICT_NAME";

                IDataReader rdr = dbManager.ExecuteReader(CommandType.Text, strSQL);

                while (rdr.Read())
                {
                    MasAmphurDAL ampDAL = new MasAmphurDAL();
                    MasAmphurInfo ampInfo = new MasAmphurInfo();
                    if (!rdr.IsDBNull(3))
                    {
                        IList<MasAmphurInfo> ampList = ampDAL.ListAmphurs(new MasAmphurInfo(rdr.IsDBNull(3) ? 0 : rdr.GetInt32(3)));
                        if (ampList.Count > 0)
                            ampInfo = ampList[0];
                    }

                    MasDistrictInfo Info = new MasDistrictInfo(rdr.IsDBNull(0) ? (int?)null : rdr.GetInt32(0)
                            , rdr.IsDBNull(1) ? "" : rdr.GetString(1)
                            , rdr.IsDBNull(2) ? "" : rdr.GetString(2)
                            , ampInfo
                            , rdr.IsDBNull(4) ? (int?)null : rdr.GetInt32(4)
                            , rdr.IsDBNull(5) ? (int?)null : rdr.GetInt32(5));
                    infoList.Add(Info);
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                dbManager.CloseReader();
                dbManager.Dispose();
            }
            return infoList;
        }
        public void Insert(MasDistrictInfo info)
        {
            string strSQL;

            try
            {
                dbManager.Open();
                dbManager.BeginTransaction();
                dbManager.CreateParameters(6);

                dbManager.AddParameters(0, "@Name", info.Name);
                dbManager.AddParameters(1, "@NameEng", info.NameEng);
                dbManager.AddParameters(2, "@Amphur", info.Amphurs.Sequence);
                dbManager.AddParameters(3, "@RecordStatus", SystemInfo._ActiveRecordStatus);
                dbManager.AddParameters(4, "@CreatedBy", info.CreatedBy);
                dbManager.AddParameters(5, "@CreatedWhen", DateTime.Today);

                strSQL = "INSERT INTO MAS_DISTRICTS(DISTRICT_NAME, DISTRICT_NAME_ENG, AMP_SEQ"
                        + ", RECORD_STATUS, CREATED_BY, CREATED_WHEN)"
                    + " VALUES(@Name, @NameEng, @Amphur, @RecordStatus, @CreatedBy, @CreatedWhen)";

                dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                dbManager.CommitTransaction();
            }
            catch
            {
                dbManager.RollBackTransaction();
                throw;
            }
            finally
            {
                dbManager.Dispose();
            }
        }

        public void Update(MasDistrictInfo info)
        {
            string strSQL;

            try
            {
                dbManager.Open();
                dbManager.BeginTransaction();
                dbManager.CreateParameters(6);

                dbManager.AddParameters(0, "@Seq", info.Sequence);
                dbManager.AddParameters(1, "@Name", info.Name);
                dbManager.AddParameters(2, "@NameEng", info.NameEng);
                dbManager.AddParameters(3, "@Amphur", info.Amphurs.Sequence);
                dbManager.AddParameters(4, "@UpdatedBy", info.UpdatedBy);
                dbManager.AddParameters(5, "@UpdatedWhen", DateTime.Today);

                strSQL = "UPDATE MAS_DISTRICTS"
                           + " SET DISTRICT_NAME = @Name"
                                + ", DISTRICT_NAME_ENG = @NameEng"
                                + ", AMP_SEQ = @Amphur"
                                + ", UPDATED_BY = @UpdatedBy"
                                + ", UPDATED_WHEN = @UpdatedWhen"
                           + " WHERE DISTRICT_SEQ = @Seq";

                dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                dbManager.CommitTransaction();
            }
            catch
            {
                dbManager.RollBackTransaction();
                throw;
            }
            finally
            {
                dbManager.Dispose();
            }
        }

        public void Delete(int Sequence, int UpdatedBy)
        {
            string strSQL;

            try
            {
                dbManager.Open();
                dbManager.BeginTransaction();
                dbManager.CreateParameters(4);

                dbManager.AddParameters(0, "@seq", Sequence);
                dbManager.AddParameters(1, "@record_status", SystemInfo._DeleteRecordStatus);
                dbManager.AddParameters(2, "@updated_by", UpdatedBy);
                dbManager.AddParameters(3, "@updated_when", DateTime.Today);

                strSQL = "UPDATE MAS_DISTRICTS"
                    + " SET RECORD_STATUS = @record_status"
                        + ", UPDATED_BY = @updated_by"
                        + ", UPDATED_WHEN = @updated_when"
                    + " WHERE DISTRICT_SEQ = @seq";

                dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                dbManager.CommitTransaction();
            }
            catch
            {
                dbManager.RollBackTransaction();
                throw;
            }
            finally
            {
                dbManager.Dispose();
            }
        }
        //public DataTable SelectDropDownList()
        //{
        //    string strSQL;
        //    DataTable dtb = null;

        //    try
        //    {
        //        dbManager.Open();
        //        dbManager.CreateParameters(1);
                
        //        dbManager.AddParameters(0, "@DeleteRecord", SystemInfo._DeleteRecordStatus);

        //        strSQL = "SELECT d.DISTRICT_SEQ, d.DISTRICT_NAME"
        //            + ", a.AMP_NAME, p.PROV_NAME, c.COUNTRY_NAME"
        //            + ", CONCAT(d.DISTRICT_NAME, ' ', a.AMP_NAME, ' ', p.PROV_NAME, ' ', c.COUNTRY_NAME) AS DISTRICT_TEXT"
        //            + " FROM MAS_DISTRICTS d"
        //            + " INNER JOIN MAS_AMPHURS a ON d.AMP_SEQ = a.AMP_SEQ"
        //            + " INNER JOIN MAS_PROVINCES p ON a.PROV_SEQ = p.PROV_SEQ"
        //            + " INNER JOIN MAS_COUNTRIES c ON p.COUNTRY_SEQ = c.COUNTRY_SEQ"
        //            + " WHERE d.RECORD_STATUS not like @DeleteRecord"
        //            + " ORDER BY DISTRICT_NAME";

        //        dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
        //    }
        //    catch
        //    {
        //        throw;
        //    }
        //    finally
        //    {
        //        dbManager.Dispose();
        //    }

        //    return dtb;
        //}

        //public DataTable SelectDropDownList(int country_seq)
        //{
        //    string strSQL;
        //    DataTable dtb = null;

        //    try
        //    {
        //        dbManager.Open();
        //        dbManager.CreateParameters(1);

        //        dbManager.AddParameters(0, "@DeleteRecord", SystemInfo._DeleteRecordStatus);
        //        dbManager.AddParameters(1, "@CountrySeq", country_seq);

        //        strSQL = "SELECT d.DISTRICT_SEQ, a.AMP_SEQ, p.PROV_SEQ"
        //            + ", CONCAT(d.DISTRICT_NAME, ' ', a.AMP_NAME, ' ', p.PROV_NAME) AS DISTRICT_TEXT"
        //            + " FROM MAS_DISTRICTS d"
        //            + " INNER JOIN MAS_AMPHURS a ON d.AMP_SEQ = a.AMP_SEQ"
        //            + " INNER JOIN MAS_PROVINCES p ON a.PROV_SEQ = p.PROV_SEQ"
        //            + " INNER JOIN MAS_COUNTRIES c ON p.COUNTRY_SEQ = c.COUNTRY_SEQ"
        //            + " WHERE d.RECORD_STATUS not like @DeleteRecord"
        //                + " AND r.COUNTRY_SEQ = @CountrySeq"
        //            + " ORDER BY d.DISTRICT_NAME, a.AMP_NAME, p.PROV_NAME";

        //        dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
        //    }
        //    catch
        //    {
        //        throw;
        //    }
        //    finally
        //    {
        //        dbManager.Dispose();
        //    }

        //    return dtb;
        //}

        //public DataTable SelectTreeView()
        //{
        //    string strSQL;
        //    DataTable dtb = null;

        //    try
        //    {
        //        dbManager.Open();
        //        dbManager.CreateParameters(1);

        //        dbManager.AddParameters(0, "@DeleteRecord", SystemInfo._DeleteRecordStatus);

        //        strSQL = "SELECT COUNTRY_SEQ AS CHILD, null AS PARENT"
        //            + ", COUNTRY_SEQ AS SEQ, COUNTRY_NAME AS NAME"
        //            + " FROM MAS_COUNTRIES"
        //            + " WHERE RECORD_STATUS not like @DeleteRecord"

        //            + " UNION ALL"

        //            + " SELECT PROV_SEQ AS CHILD, COUNTRY_SEQ AS PARENT"
        //            + ", PROV_SEQ AS SEQ, PROV_NAME AS NAME"
        //            + " FROM MAS_PROVINCES"
        //            + " WHERE RECORD_STATUS not like @DeleteRecord"

        //            + " UNION ALL"

        //            + " SELECT AMP_SEQ AS CHILD, PROV_SEQ AS PARENT"
        //            + ", AMP_SEQ AS SEQ, AMP_NAME AS NAME"
        //            + " FROM MAS_AMPHURS"
        //            + " WHERE RECORD_STATUS not like @DeleteRecord"

        //            + " UNION ALL"

        //            + " SELECT DISTRICT_SEQ AS CHILD, AMP_SEQ AS PARENT"
        //            + ", DISTRICT_SEQ AS SEQ, DISTRICT_NAME AS NAME"
        //            + " FROM MAS_DISTRICTS"
        //            + " WHERE RECORD_STATUS not like @DeleteRecord";

        //        dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
        //    }
        //    catch
        //    {
        //        throw;
        //    }
        //    finally
        //    {
        //        dbManager.Dispose();
        //    }

        //    return dtb;
        //}
    }
}
